﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using WeiBOAPI.Sina;
using WeiBOAPI.Threads;
using NLog;

namespace WeiBOAPI.Common
{
    public class HttpHelper
    {
        private static Logger logger = LogManager.GetCurrentClassLogger(); 

        public void DoGetRequest(string url, SinaAPI sBussiceType)
        {
            try
            {
                RequestState rqs = new RequestState();
                rqs._sBussiceType = sBussiceType;
                rqs._request = (HttpWebRequest)WebRequest.Create(url);
                rqs._request.BeginGetResponse(new AsyncCallback(DoGetResponse), rqs);
            }
            catch (System.InvalidOperationException ex)
            {
                logger.Error(ex.Message);
            }
            
        }

        public void DoPostRequest(string url, SinaAPI sBussiceType, string postData)
        {
            try
            {
                Encoding encoding = Encoding.GetEncoding("utf-8");
                byte[] bytesToPost = encoding.GetBytes(postData);
                RequestState rqs = new RequestState();
                rqs._sBussiceType = sBussiceType;
                rqs._request = (HttpWebRequest)WebRequest.Create(url);
                rqs._request.Method = "POST";
                rqs._request.Headers.Add("API-RemoteIP", "127.0.0.1");
                rqs._request.ServicePoint.Expect100Continue = false;
                rqs._request.ContentType = "application/x-www-form-urlencoded";
                rqs._request.ContentLength = bytesToPost.Length;
                StreamWriter streamWriter = new StreamWriter(rqs._request.GetRequestStream());
                streamWriter.Write(postData);
                streamWriter.Close();
                rqs._request.BeginGetResponse(new AsyncCallback(DoGetResponse), rqs);
            }
            catch (System.InvalidOperationException ex)
            {
                logger.Error(ex.Message);
            }

        }

        private void DoGetResponse(IAsyncResult asynObj)
        {
            try
            {
                RequestState myRequestState = asynObj.AsyncState as RequestState;
                HttpWebRequest myHttpWebRequest2 = myRequestState._request;
                myRequestState._response = (HttpWebResponse)myHttpWebRequest2.EndGetResponse(asynObj);
                Stream responseStream = myRequestState._response.GetResponseStream();
                myRequestState._streamResponse = responseStream;
                responseStream.BeginRead(myRequestState._bufferRead, 0, RequestState.BUFFER_SIZE
                    , new AsyncCallback(ReadCallBack), myRequestState);
            }
            catch (System.InvalidOperationException ex)
            {
                logger.Error(ex.Message);
            }
            
        }

        

        private void ReadCallBack(IAsyncResult asyncResult)
        {
            try
            {
                RequestState myRequestState = (RequestState)asyncResult.AsyncState;
                Stream responseStream = myRequestState._streamResponse;
                int read = responseStream.EndRead(asyncResult);

                if (read > 0)
                {
                    myRequestState._requestData.Append(Encoding.UTF8.GetString(
                        myRequestState._bufferRead, 0, read));

                    IAsyncResult asynchronousResult = responseStream.BeginRead(
                        myRequestState._bufferRead, 0, RequestState.BUFFER_SIZE,
                        new AsyncCallback(ReadCallBack), myRequestState);
                    return;
                }
                else
                {
                    // 业务处理
                    if (myRequestState._requestData.Length > 1)
                    {
                        string stringContent;
                        stringContent = myRequestState._requestData.ToString();
                        Global.Instance._g_thrParse._parseQueue.Enqueue(
                            new ParseArg(myRequestState._sBussiceType, stringContent, ""));
                        Global.Instance._g_thrParse._mEvent.Set();
                    }
                    responseStream.Close();
                }

            }
            catch (IOException e)
            {
                logger.Error(e.Message);
            }
            catch (WebException e)
            {
                logger.Error(e.Message);
            }
        }
    }

    public class RequestState
    {
        public const int BUFFER_SIZE = 1024;
        public StringBuilder _requestData;
        public byte[] _bufferRead;
        public HttpWebRequest _request;
        public HttpWebResponse _response;
        public Stream _streamResponse;
        public SinaAPI _sBussiceType;
        public RequestState()
        {
            _bufferRead = new byte[BUFFER_SIZE];
            _requestData = new StringBuilder("");
            _request = null;
            _streamResponse = null;
        }
    }
}
